package com.ccc.controller;


import com.ccc.entity.StuLog;
import com.ccc.mapper.StuLogMapper;
import com.ccc.utils.JwtUtil;
import com.ccc.utils.ResponseResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ccc
 * @since 2021-12-27
 */
@Controller
public class StuLogController {

    @Autowired
    StuLogMapper stuLogMapper;

    /**
     * 教师获取学生日志表，返回的是所有学生的日志
     *
     * @return
     */
    @GetMapping("/teacher/stulog")
    @PreAuthorize("hasAuthority('teacher')")
    @ResponseBody
    public ResponseResult logList() {
        return new ResponseResult(200, "success", stuLogMapper.logList());
    }

    /**
     * 学生获取日志，返回的是请求的学生的日志
     */
    @GetMapping("/stu/logs")
    @PreAuthorize("hasAuthority('student')")
    @ResponseBody
    public ResponseResult stuGetLogs(HttpServletRequest request) {
        String token = request.getHeader("token");

        String username;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(400, "token Error!");
        }
        return new ResponseResult(200, "success", stuLogMapper.stuGetLogsById(username));
    }

    /**
     * 学生添加日志
     */
    @PostMapping("/stu/addLog")
    @PreAuthorize("hasAuthority('student')")
    @ResponseBody
    public ResponseResult addLog(@RequestBody StuLog stuLog, HttpServletRequest request) {
        String token = request.getHeader("token");

        String username;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(400, "token Error!");
        }
        stuLogMapper.addLog(username, stuLog.getTitle(), stuLog.getDateFrom(), stuLog.getDateTo(), stuLog.getContent());
        return new ResponseResult(200, "success");
    }

}
